package nl.sanity.net
{	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	import nl.sanity.events.XMLLoaderEvent;
	
	import nl.sanity.debug.LogConsole;
	
 	/**
	 * XMLLoader
	 * 
	 * @langversion ActionScript 3
	 *
	 * @author M.P. Bartnig
	 * @since  28/03/2009
	 */
	public class XMLLoader extends EventDispatcher
	{
		public static var NAME		: String	= "XMLLoader";
		public static var DEBUG		: Boolean	= false;
		
		protected var loader		: URLLoader;
		protected var _xml			: XML;
		protected var _autoStart 	: Boolean;
		protected var _useCache 	: Boolean;
		protected var _url			: String;
		
		// --- CONSTRUCTOR ----------------------------------------
		
		public function XMLLoader( url:String = null, autoStart:Boolean = true, useCache:Boolean = true )
		{
			_autoStart		= autoStart;
			_useCache		= useCache;
			
			if ( _autoStart && url ) load ( url );
		}
		
		// --- PUBLIC FUNCTIONS ----------------------------------------

		public function load( url:String ):void
		{
			if ( !_useCache ) url += "?ts=" + getTimeStamp();
			
			loader = new URLLoader();

			loader.addEventListener( Event.COMPLETE, onLoadComplete, false, 0, true );
			loader.addEventListener( IOErrorEvent.IO_ERROR, onLoadError, false, 0, true );
			
			if ( DEBUG ) LogConsole.info( NAME + ".load | url=" + url );
			
			loader.load( new URLRequest( url ) );
		}
		
		// --- PROTECTED FUNCTIONS ----------------------------------------

		protected function removeListeners():void
		{
			loader.removeEventListener( Event.COMPLETE, onLoadComplete );
			loader.removeEventListener( IOErrorEvent.IO_ERROR, onLoadError );
		}
		
		protected function onLoadComplete( event:Event ):void
		{
			removeListeners();
			
			_xml = XML( URLLoader( event.target ).data );
		
			if ( DEBUG ) LogConsole.info( NAME + ".onLoadComplete | Loaded XML:\n" + _xml );
			
			dispatchEvent( new XMLLoaderEvent( XMLLoaderEvent.ON_COMPLETE, _xml ) );
		}	
		
		protected function onLoadError( event:IOErrorEvent ):void
		{
			removeListeners();
			
			dispatchEvent( new XMLLoaderEvent( XMLLoaderEvent.ON_ERROR ) );
		}
		
		// --- PRIVATE FUNCTIONS ----------------------------------------

		private function getTimeStamp():String
		{
			return new Date().getTime().toString();
		}
		
		// --- GETTERS / SETTERS ------------------------------------------------------------------------------------
		
		public function get xml():XML { return _xml; }
		
		public function get url():String { return _url; }
		
		public function set url( url:String ):void { _url = url; }
		
	}
}